"use strict";
import axios from "axios";
import { log, unifyCode } from "@/utils";
import store from "@/store";
import router from "@/router";

// 创建axios实例
export function createAxios(opt = {}) {
  const service = axios.create({
    baseURL: opt.baseURL,
    timeout: 30000
  });

  service.interceptors.request.use(
    (config) => {
      if (store.getters.token) {
        config.headers[process.env.VUE_APP_TOKEN_KEY] = store.getters.token;
      }
      return config;
    },
    (error) => {
      log(error);
      return Promise.reject(error);
    }
  );

  service.interceptors.response.use(
    (response) => {
      if (response.config.responseType === "blob") {
        let name = response.headers["content-disposition"] || "";
        let ret = name.match(/filename=([^;]*)/);
        response.filename = decodeURIComponent((ret && ret[1]) || "blob");
        return response;
      }
      const res = unifyCode(response.data); //统一接口返回数据格式
      if (res.retcode && res.retcode !== 0) {
        if (res.retcode === 403) {
          setTimeout(() => {
            router.replace("/login");
          }, 1000);
        }
        return Promise.reject({ msg: res.msg || "Error" });
      } else {
        return res;
      }
    },
    (error) => {
      if (error.response && error.response.status === 403) {
        router.replace("/login");
        return Promise.reject({ msg: "登录信息失效" });
      } else {
        return Promise.reject({ msg: "Error" });
      }
    }
  );

  return service;
}

export default createAxios({
  baseURL: process.env.VUE_APP_SERVER
});
